package com.hl.reflect;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class ReflectApp02 {

    /**
     * 反射的作用
     *      1. 获取一个类里面的所有信息（包括成员变量，方法，构造器），再执行其他业务逻辑
     *      2. 动态创建对象并调用方法，从配置文件读取类和方法的信息
     * 针对 2，需求如下
     *      在配置文件 config.properties 中配置好，要执行的 类名className 和 方法名classMethod，动态创建该对象并执行方法
     *
     */
    public static void main(String[] args) throws IOException, NoSuchMethodException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // read file config.properties
        Properties properties = new Properties();
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\liuhuan22\\Documents\\ideaPrjHL\\HelloSpring\\src\\main\\resources\\config.properties");
        properties.load(fileInputStream);
        fileInputStream.close();
        System.out.println("properties = " + properties);

        // get var
        String className = (String) properties.get("className");
        String methodName = (String) properties.get("methodName");

        // get class
        Class<?> clazz = Class.forName(className);

        // create obj
        Constructor<?> constructor = clazz.getConstructor();
        Object obj = constructor.newInstance();

        // get method
        Method declaredMethod = clazz.getDeclaredMethod(methodName, String.class);

        // invoke method
        declaredMethod.setAccessible(true);
        Object result = declaredMethod.invoke(obj, "java 讲义");
        System.out.println("result = " + result);
    }


}
